package com.yutou.droid;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

import com.luckyboy.mmxing.R;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startJarActivity();
            }
        });
    }

    /**
     * 尝试直接启动jar包中的Activity
     */
    public void startJarActivity(){
        try{
            Class activity=getClassLoader().loadClass("com.yutou.plug.ActivityTest");
            Intent intent=new Intent(MainActivity.this,activity);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 测试带有接口的方法。。。玩不来，如果接口方法带有传参或返回值的话，会炸的
     */
    private void startJarListener(){
        try{
            Class dataClass=getClassLoader().loadClass("com.yutou.plug.Data");
            Class jarListener=getClassLoader().loadClass("com.yutou.plug.MyInterface");
            Object data=dataClass.newInstance();
            MyListener listener=new MyListener(data);
            Object myListener= Proxy.newProxyInstance(getClassLoader(),new Class[]{jarListener},listener);

            Method method=data.getClass().getMethod("setListener", new Class[]{jarListener});
            method.setAccessible(true);
            method.invoke(data,myListener);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 反射获取参数
     */
    private void startJarData(){
        try{
            Class dataClass=getClassLoader().loadClass("com.yutou.plug.Data");
            Object data=dataClass.newInstance();
            Method method=data.getClass().getMethod("getName", null);
            String uName= (String) method.invoke(data,null);
            System.out.println("uName = " + uName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
